package com.java.thread.group.sync;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class AsyncMultipleThreadsSingleUrl {
    private static final String URL = "https://www.example.com";
    private static final int THREAD_COUNT = 5;

    public static void main(String[] args) {
        // 创建一个固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
        List<CompletableFuture<String>> futures = new ArrayList<>();

        // 提交多个异步任务
        for (int i = 0; i < THREAD_COUNT; i++) {
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                try {
                    return sendRequest(URL);
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }, executor);
            futures.add(future);
        }

        // 等待所有任务完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        CompletableFuture<List<String>> allResults = allFutures.thenApply(v -> {
            return futures.stream()
                    .map(CompletableFuture::join)
                    .collect(Collectors.toList());
        });

        try {
            // 获取所有任务的结果
            List<String> results = allResults.get(10, TimeUnit.SECONDS);
            for (int i = 0; i < results.size(); i++) {
                System.out.println("Result from thread " + (i + 1) + ": " + results.get(i).substring(0, Math.min(results.get(i).length(), 50)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            executor.shutdown();
        }
    }

    private static String sendRequest(String urlStr) throws Exception {
        // 创建 URL 对象
        URL url = new URL(urlStr);
        // 打开 HTTP 连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置请求方法为 GET
        connection.setRequestMethod("GET");

        // 读取响应内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        System.out.println("成功打印");
        // 关闭输入流
        reader.close();
        return response.toString();
    }
}